using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using UserManagement.Models;
using UserManagement.Services;

namespace UserManagement.ViewModels
{
    public class UserListViewModel : BindableBase, INavigationAware
    {
        private readonly IUserService _userService;
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        
        private ObservableCollection<User> _users = new();
        private User? _selectedUser;
        private string _statusMessage = "准备就绪";

        public UserListViewModel(IUserService userService, IRegionManager regionManager, IDialogService dialogService)
        {
            _userService = userService;
            _regionManager = regionManager;
            _dialogService = dialogService;

            // 初始化Commands
            RefreshCommand = new DelegateCommand(async () => await RefreshUsersAsync());
            AddUserCommand = new DelegateCommand(AddUser);
            EditUserCommand = new DelegateCommand<User>(EditUser);
            DeleteUserCommand = new DelegateCommand<User>(async (user) => await DeleteUserAsync(user));
        }

        #region Properties

        public ObservableCollection<User> Users
        {
            get { return _users; }
            set { SetProperty(ref _users, value); }
        }

        public User? SelectedUser
        {
            get { return _selectedUser; }
            set { SetProperty(ref _selectedUser, value); }
        }

        public string StatusMessage
        {
            get { return _statusMessage; }
            set { SetProperty(ref _statusMessage, value); }
        }

        #endregion

        #region Commands

        public DelegateCommand RefreshCommand { get; }
        public DelegateCommand AddUserCommand { get; }
        public DelegateCommand<User> EditUserCommand { get; }
        public DelegateCommand<User> DeleteUserCommand { get; }

        #endregion

        #region Command Methods

        private async Task RefreshUsersAsync()
        {
            try
            {
                StatusMessage = "正在加载用户...";
                var users = await _userService.GetAllUsersAsync();
                Users.Clear();
                foreach (var user in users)
                {
                    Users.Add(user);
                }
                StatusMessage = $"已加载 {Users.Count} 个用户";
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载用户失败: {ex.Message}";
            }
        }

        private void AddUser()
        {
            _regionManager.RequestNavigate("ContentRegion", "AddUserView");
        }

        private void EditUser(User user)
        {
            if (user != null)
            {
                var parameters = new NavigationParameters
                {
                    { "UserId", user.Id }
                };
                _regionManager.RequestNavigate("ContentRegion", "AddUserView", parameters);
            }
        }

        private async Task DeleteUserAsync(User user)
        {
            if (user == null) return;

            var parameters = new DialogParameters
            {
                { "title", "确认删除" },
                { "message", $"您确定要删除用户 '{user.Name}' 吗？" }
            };

            _dialogService.ShowDialog("ConfirmationDialog", parameters, async (result) =>
            {
                if (result.Result == ButtonResult.OK)
                {
                    try
                    {
                        StatusMessage = "正在删除用户...";
                        var success = await _userService.DeleteUserAsync(user.Id);
                        if (success)
                        {
                            Users.Remove(user);
                            StatusMessage = "用户删除成功";
                        }
                        else
                        {
                            StatusMessage = "用户删除失败";
                        }
                    }
                    catch (Exception ex)
                    {
                        StatusMessage = $"删除用户失败: {ex.Message}";
                    }
                }
            });
        }

        #endregion

        #region INavigationAware

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 当导航到此视图时，刷新数据
            RefreshCommand.Execute();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 离开视图时的清理工作
        }

        #endregion
    }
}